package com.up.upzl.biz.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up.upzl.biz.domain.Module;
import com.up.upzl.biz.domain.Module.PageType;
import com.up.upzl.biz.domain.Module.ShowType;
import com.up.upzl.biz.service.ModuleService;



/**
 * 模块管理
 * 
 * @author youke
 *
 */

@Controller
@RequestMapping("pageModule")
public class PageModuleController {
	
	@Autowired
	private ModuleService moduleService;
	
	/**
	 * 首页展示管理列表
	 * 
	 * @author youke
	 *
	 */
	@GetMapping("list")
	public String List(String name, ShowType showType, Pageable page, Model model) {
		PageType pageType = PageType.首页;
		Page<Module> list = moduleService.findByCondition(pageType, showType, name, page);
		model.addAttribute("pageList", list);
		return "pageModule/list";
	}
	
	/**
	 * 跳转到首页展示添加页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("addPage")
	public String add(Model model) {
		
		ShowType[] showTypeEnum =  ShowType.values();
		model.addAttribute("showType" , showTypeEnum);
		
		model.addAttribute("pageType" , PageType.首页);
		return "pageModule/add";
	}
	

	/**
	 * 保存对象
	 */
	@PostMapping("add")
	public @ResponseBody Module save(Module module) {
		return moduleService.save(module);
	}

	/**
	 * 跳转到更新页面
	 */
	@GetMapping({ "updatePage", "detail" })
	public String update(Long id, Model model) {
		Module module = moduleService.findOne(id);
		model.addAttribute("entity", module);
		
		ShowType[] showTypeEnum =  ShowType.values();
		model.addAttribute("showType" , showTypeEnum);
		
		return "pageModule/update";
	}

	/**
	 * 更新
	 */
	@PostMapping("update")
	public @ResponseBody Module update(Module module) {
		Assert.notNull(module.getId(), "Id can`t be null");
		return moduleService.save(module);
	}

	/**
	 * 删除
	 */
	@PostMapping("delete")
	public @ResponseBody Map<String, String> delete(Module module) {
		Assert.notNull(module.getId(), "Id can`t be null");
		Map<String, String> map = new HashMap<>();
		try {
			moduleService.delete(module.getId());
		} catch (Exception e) {
			map.put("Type", "500");
			return map;
		}
		map.put("Type", "200");
		return map;
	}

}
